package com.breeze.components.socket.redis;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.breeze.components.socket.WebSocketManager;
import com.breeze.components.socket.redis.action.Action;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

/**
 * 默认redis 消息接收者
 *
 * @author breeze
 */
@Slf4j
public record DefaultRedisReceiver(ApplicationContext applicationContext) implements RedisReceiver {

  public DefaultRedisReceiver(@NonNull ApplicationContext applicationContext) {
    this.applicationContext = applicationContext;
  }

  /** 此方法会被反射调用 */
  @Override
  public void receiveMessage(String message) {
    log.debug("redis接收到消息:{}", message);
    JSONObject object = JSON.parseObject(message);
    if (!object.containsKey(Action.ACTION)) {
      return;
    }
    String actionName = object.getString(Action.ACTION);
    Action action = getAction(actionName);
    action.doMessage(getWebSocketManager(), object);
  }

  private Action getAction(String actionName) {
    return applicationContext().getBean(actionName, Action.class);
  }

  private WebSocketManager getWebSocketManager() {
    return applicationContext()
        .getBean(WebSocketManager.WEBSOCKET_MANAGER_NAME, WebSocketManager.class);
  }
}
